
import clientPromise from '@/libs/mongoClient';
import { buildPaginationResponse } from '@/libs/pagination';
import { NextApiResponse } from '@/libs/apiResponse';
import { ObjectId, type Filter } from 'mongodb';
import { type NextRequest } from 'next/server';
import { z } from 'zod';

export interface FlowData {
  code: string;
  name: string;
  aiAnalysisText: string;
  imageUrl: string;
}

// 数据库文档类型（服务端使用）
export interface FlowDocument extends FlowData {
  _id: ObjectId;
  createdAt?: Date;
  updatedAt?: Date;
}

export interface FlowVO extends FlowData {
  _id: string;
}

const CreateFlowSchema = z.object({
  code: z.string().min(1, '工艺编码不能为空'),
  name: z.string().min(1, '工艺简称不能为空'),
  imageUrl: z.string().min(1, '图片不能为空'),
  aiAnalysisText: z.string().min(1, 'AI分析不能为空'),
});

export type CreateFlowInput = z.infer<typeof CreateFlowSchema>;

const UpdateFlowSchema = CreateFlowSchema.partial().extend({
  id: z.string().min(1, 'id 不能为空'),
});

const QuerySchema = z.object({
  id: z.string().optional(),
  page: z.coerce.number().min(1).default(1),
  pageSize: z.coerce.number().min(1).max(100).default(10),
  search: z.string().optional(),
});

// GET /api/flows 获取所有工艺流程
export async function GET(request: NextRequest) {
  try {


    const searchParams = Object.fromEntries(request.nextUrl.searchParams);
    const query = QuerySchema.parse(searchParams);

    const db = (await clientPromise).db('ruanzhu_template');

    const filter: Filter<FlowDocument> = {};

    if (query.search && query.search.trim()) {
      const searchRegex = new RegExp(query.search.trim(), 'i');

      filter.$or = [
        { code: searchRegex }, // 在标题中搜索
        { name: searchRegex }, // 在内容中搜索
      ];
    }

    const collection = db.collection<FlowDocument>('flows');

    if (query.id) {
      if (!ObjectId.isValid(query.id)) {
        return NextApiResponse.badRequest('无效的工艺流程ID');
      }

      const flow = await collection.findOne({ _id: new ObjectId(query.id) });
      if (!flow) {
        return NextApiResponse.notFound('工艺流程不存在');
      }

      return NextApiResponse.success(flow, '获取成功');
    }

    const flows = await collection
      .find(filter)
      .skip((query.page - 1) * query.pageSize)
      .limit(query.pageSize)
      .sort({
        createdAt: -1,
      })
      .toArray();

    const total = await db.collection('flows').countDocuments();
    const data = buildPaginationResponse(flows, total, {
      page: query.page,
      pageSize: query.pageSize,
    });

    return NextApiResponse.success(data, '获取成功');
  } catch (error) {
    console.error(error);

    if (error instanceof z.ZodError) {
      return NextApiResponse.error('请求参数验证失败');
    }

    return NextApiResponse.serverError('服务器内部错误');
  }
}

// POST /api/flows 上传工艺流程
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const validatedData = CreateFlowSchema.parse(body);

    const flowDoc: Omit<FlowDocument, '_id'> = {
      ...validatedData,
    };

    const db = (await clientPromise).db('ruanzhu_template');
    const result = await db.collection('flows').insertOne(flowDoc);

    return NextApiResponse.created(
      {
        id: result.insertedId.toString(),
        ...flowDoc,
      },
      '工艺流程创建成功'
    );
  } catch (error) {
    console.error('出错了:', error);

    if (error instanceof z.ZodError) {
      return NextApiResponse.badRequest('请求参数验证失败');
    }

    return NextApiResponse.serverError('服务器内部错误');
  }
}

// PUT /api/flows 更新工艺流程
export async function PUT(request: NextRequest) {
  try {
    const body = await request.json();

    const validatedData = UpdateFlowSchema.parse(body);

    if (!ObjectId.isValid(validatedData.id)) {
      return NextApiResponse.badRequest('无效的工艺流程ID');
    }

    const db = (await clientPromise).db('ruanzhu_template');
    const collection = db.collection('flows');

    const { id, ...updatedData } = validatedData;

    if (updatedData.code) {
      const existingFlow = await collection.findOne({
        code: updatedData.code,
        _id: { $ne: new ObjectId(id) },
      });

      if (existingFlow) {
        return NextApiResponse.badRequest('工艺编码已存在');
      }
    }

    const result = await collection.updateOne(
      { _id: new ObjectId(id) },
      {
        $set: {
          ...updatedData,
        },
      }
    );

    if (result.matchedCount === 0) {
      return NextApiResponse.notFound('工艺流程不存在');
    }

    return NextApiResponse.success(
      {
        id,
      },
      '工艺流程更新成功'
    );
  } catch (error) {
    console.error('出错了:', error);

    if (error instanceof z.ZodError) {
      return NextApiResponse.badRequest('请求参数验证失败');
    }

    return NextApiResponse.serverError('服务器内部错误');
  }
}

// DELETE /api/flows 删除工艺流程
export async function DELETE(request: NextRequest) {
  const id = request.nextUrl.searchParams.get('id');

  if (!id) {
    return NextApiResponse.badRequest('缺少必要参数id');
  }

  if (!ObjectId.isValid(id)) {
    return NextApiResponse.badRequest('无效的工艺流程ID');
  }

  const db = (await clientPromise).db('ruanzhu_template');
  const collection = db.collection<FlowDocument>('flows');

  const result = await collection.deleteOne({
    _id: new ObjectId(id),
  });

  if (result.deletedCount === 0) {
    return NextApiResponse.notFound('工艺流程不存在');
  }

  return NextApiResponse.success(null, '工艺流程删除成功');
}
